package com.paic.icore.test.demo.util;

import org.apache.commons.lang.StringUtils;

import javax.crypto.*;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;

public class AESUtil {
    public static Charset charset = Charset.forName("UTF-8");

    public static final String ALGORITHM = "AES";

    //可配置的密钥
    public static byte[] keybyte = "ST_Centurio@2021".getBytes();

    public static SecretKey generateKey() throws NoSuchAlgorithmException { // 生成密钥
        KeyGenerator secretGenerator = KeyGenerator.getInstance(ALGORITHM);
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(keybyte);
        secretGenerator.init(128, secureRandom);
        SecretKey secretKey = secretGenerator.generateKey();
        return secretKey;
    }

    /**
     * AES加密并返回Base64
     *
     * @param content
     */
    public static String encryptBase64(String content) {
        if (StringUtils.isEmpty(content)) {
            return "";
        }
        try {
            return Base64.getEncoder().encodeToString(aes(content.getBytes(charset), Cipher.ENCRYPT_MODE, generateKey()));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content;
    }

    /**
     * AES加密并返回Base64
     *
     * @param content
     * @param secretKey
     */
    public static String encryptBase64(String content, SecretKey secretKey) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { // 加密
        if (StringUtils.isEmpty(content)) {
            return "";
        }
        return Base64.getEncoder().encodeToString(aes(content.getBytes(charset), Cipher.ENCRYPT_MODE, secretKey));
    }

    /**
     * AES解密
     *
     * @param base64Str
     */
    public static String decryptBase64(String base64Str) {
        if (StringUtils.isEmpty(base64Str)) {
            return "";
        }
        try {
            byte[] decrypt = Base64.getDecoder().decode(base64Str.getBytes());
            byte[] result = aes(decrypt, Cipher.DECRYPT_MODE, generateKey());
            return new String(result, charset);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return base64Str;
    }

    /**
     * AES解密
     *
     * @param base64Str
     * @param secretKey
     */
    public static String decryptBase64(String base64Str, SecretKey secretKey) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { // 解密
        if (StringUtils.isEmpty(base64Str)) {
            return "";
        }
        byte[] decrypt = Base64.getDecoder().decode(base64Str.getBytes());
        byte[] result = aes(decrypt, Cipher.DECRYPT_MODE, secretKey);
        return new String(result, charset);
    }

    private static byte[] aes(byte[] contentArray, int mode, SecretKey secretKey)
            throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(mode, secretKey);
        byte[] result = cipher.doFinal(contentArray);
        return result;
    }

    public static void main(String[] args) {
        String content = "440306200005238919";
        SecretKey secretKey;
        try {
            long timeStart = System.currentTimeMillis();
            secretKey = generateKey();
            String encryptResult = encryptBase64(content);
            long timeEnd = System.currentTimeMillis();
            System.out.println("加密用时：" + (timeEnd - timeStart));
            System.out.println("加密后的结果为：" + encryptResult);
            long enTimeStart = System.currentTimeMillis();
            String decryptResult = decryptBase64("26qmGyIohcMOIRSNAVF1Zw==");
            System.out.println("解密后的结果为：" + decryptResult);
            System.out.println("解密用时：" + (System.currentTimeMillis() - enTimeStart));
            String s = "20160426134527+0800";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssZ");
            Date parse = sdf.parse(s);
            System.out.println(parse);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
